package com.piece.core.verifycode.factory.captcha;

import com.google.code.kaptcha.Producer;
import com.piece.core.framework.properties.ApplicationProperties;
import com.piece.core.framework.constant.ApplicationConstants;
import com.piece.core.framework.constant.ParamConstants;
import com.piece.core.framework.support.convert.Convert;
import com.piece.core.framework.util.string.StringUtil;
import com.piece.core.verifycode.enums.CaptchaType;
import com.piece.core.verifycode.factory.ValidateCode;
import com.piece.core.verifycode.factory.ValidateCodeGenerator;
import com.piece.core.verifycode.properties.VerifyCodeProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 验证码生成器
 */
@Component("captchaValidateCodeGenerator")
public class CaptchaValidateCodeGenerator implements ValidateCodeGenerator {

    @Autowired
    private ApplicationProperties applicationProperties;

    @Autowired
    private VerifyCodeProperties verifyCodeProperties;

    @Resource(name = "defaultCaptcha")
    private Producer defaultCaptcha;

    @Resource(name = "defaultMathCaptcha")
    private Producer defaultMathCaptcha;

    @Override
    public ValidateCode generate(HttpServletRequest request, HttpServletResponse response) {
        String type = request.getParameter(ParamConstants.CAPTCHA_TYPE);
        if (StringUtil.isEmpty(type)) {
            type = Convert.toStr(applicationProperties.getValue(ApplicationConstants.KAPTCHA_TYPE), "char");
        }

        String mathResult, code;
        if (CaptchaType.MATH.name().equalsIgnoreCase(type)) {
            String capText = defaultMathCaptcha.createText();
            code = capText.substring(0, capText.lastIndexOf("@"));
            mathResult = capText.substring(capText.lastIndexOf("@") + 1);
        } else {
            code = mathResult = defaultCaptcha.createText();
        }
        return new ValidateCode(code, mathResult, type, verifyCodeProperties.getCodeExpire());
    }
}
